<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2018/11/18
 * Time: 21:43
 */

namespace app\storage\controller;

use app\storage\model\SupplierMaterielModel;
use app\storage\model\SupplierModel;
use cmf\controller\AdminBaseController;
use think\Request;

class SupplierController extends AdminBaseController
{
    private $supplierModel;
    use \app\storage\util\Common;

    public function __construct(Request $request,SupplierModel $supplierModel)
    {
        parent::__construct($request);
        $this->supplierModel = $supplierModel;
    }

    public function index(){
        return $this->fetch('index');
    }

    public function add(){
        $supplierId = $this->getMaxId();
        $this->assign('supplierId',$supplierId);
        return $this->fetch('add');
    }

    public function edit(){
        $uuid = input('uuid');
        $supplierInfo = $this->supplierModel->where('uuid',$uuid)->find();
        $this->assign('supplierInfo',$supplierInfo);
        return $this->fetch('edit');
    }

    public function getSupplier(){
        $where = $this->getWhere();
        $result = $this->supplierModel->getSupplier($where);
        return json($result);
    }

    public function getSupplierInventory(){
        $where = $this->getWhere();
        $where['where']['supplier_id'] = input('supplierId');
        $result = $this->supplierModel->getSupplierInventory($where);
        return json($result);
    }

    public function addSupplier(){
        $data = input();
        $data['type'] = 1;
        $data['uuid'] = create_uuid();
        $this->supplierModel->save($data);
        $this->redirect('/storage/Supplier/index');
    }

    public function deleteSupplier(){
        $uuid = input('uuid');
        $result = $this->supplierModel->deleteSupplier($uuid);
        return json($result);
    }

    public function editSupplier(){
        $data = input();
        $data['type'] = 1;
        $this->supplierModel->isUpdate(true)->save($data);
        $this->redirect('/storage/Supplier/index');
    }

    public function getMaxId(){
        $supplierId = $this->supplierModel->where(['type'=>1])->max('supplier_id');
        if(empty($supplierId) && intval($supplierId)!==0){
            $supplierId = '000000';
        }else{
            $supplierId = str_pad($supplierId+1,6,'0',STR_PAD_LEFT);
        }
        return $supplierId;
    }

    public function checkSupplierName(){
        $uuid = input('uuid');
        $whereAnd = empty($uuid) ? '' : " and $uuid != '$uuid'";
        $where = sprintf("binary company_name = '%s' $whereAnd", input('name'));
        $repeat = $this->supplierModel->where($where)->find();
        return json(boolval(count($repeat)));
    }

    public function updateInventoryFromK3()
    {
        $supplierId = input('supplierId');
        $supplierMaterielModel = new SupplierMaterielModel();
        $result = $supplierMaterielModel->updateInventoryFromK3($supplierId);
        return json($result);
    }
}